package thread;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.junit.Test;

/**
 * 时钟演示
 * @author fidel
 */
public class ClockDemo {
    private static long time;
    private static Date clock = new Date(0);
    
    @Test
    public void test() {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        // Runnable是Thread实现的接口，仅包含run方法的声明
        new Runnable() {
            @Override
            public void run() {
                while (true) {
                    synchronized (this) {
                        time = Calendar.getInstance().getTimeInMillis();
                        if (time % 1000 == 0 && clock.getTime() != time) {
                            clock.setTime(time);
                            // DateFormat.format(Date)用于将一个日期格式化为日期或时间字符串
                            System.out.println(sdf.format(clock));
                            try {
                                // 在同步代码块中，令当前线程等待990毫秒
                                this.wait(990);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        }.run();
    }
}
